package com.digitalchina.lxnsy.activity.old;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.management.EnterpriseAuthActivity;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.TIME;
import com.digitalchina.lxnsy.entity.PointVO;
import com.digitalchina.lxnsy.entity.UserVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.EncryptUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.RegexpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.widget.EditTextWithClear;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.digitalchina.lxnsy.xml.UserXML;

import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


import static com.digitalchina.lxnsy.constant.Constant.MSG_SET_ALIAS;

/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：注册页面
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2016/4/11 9:36
 * 修改备注：
 * ================================================
 */
public class RegisterActivity extends BaseActivity {


    @Bind(R.id.register_et_username)
    EditTextWithClear registerEtUsername;
    @Bind(R.id.register_et_mobile)
    EditTextWithClear registerEtMobile;
    @Bind(R.id.register_bt_auth_code)
    Button registerBtAuthCode;
    @Bind(R.id.register_et_auth_code)
    EditTextWithClear registerEtAuthCode;
    @Bind(R.id.register_et_password)
    EditTextWithClear registerEtPassword;
    @Bind(R.id.register_et_affirm_password)
    EditTextWithClear registerEtAffirmPassword;
    @Bind(R.id.register_bt_register)
    Button registerBtRegister;
    @Bind(R.id.register_et_invite_code)
    EditTextWithClear registerEtInviteCode;

    private String mStrUserName;        //用户名String
    private String mStrMobile;          //手机号String
    private String mStrAuthCode;        //验证码String
    private String mStrPassword;        //密码String
    private String mStrAffirmPassword;  //确认密码String

    private String userType = "";

    private Map<String, String> map;

    String openId = "";
    String ID = ""; // 微信ID 或者支付宝userId
    String accountType = "";


    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_register);
    }

    @Override
    public void initMember() {
        map = (Map<String, String>) getIntent().getSerializableExtra("map");
        userType = map.get("userType");
        if (map.containsKey("accountType")) {
            openId = map.get("openId");
            ID = map.get("ID");
            accountType = map.get("accountType");
        }

        if (userType.equals(Constant.USER_TYPE_PERSON))
            setTitle("普通用户注册");
        else if(userType.equals(Constant.USER_TYPE_EXPERT))
            setTitle("专家用户注册");
        else
            setTitle("企业用户注册");
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_REGISTER_AND_LOGIN_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_REGISTER_AND_LOGIN_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_SEND_VERIFY_CODE_SUCCESS:
                        Utils.startForbitSendVerifyCode(RegisterActivity.this,
                                mHandler, TIME.SEND_CHECKCODE_TIME, null);
                        break;
                    case MSG.MSG_SEND_VERIFY_CODE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_SEND_VERIFY_CODE_TIP:
                        if (isFinishing())
                            return;
                        registerBtAuthCode.setClickable(false);
                        registerBtAuthCode.setTextColor(Color.parseColor("#b3b3b3"));
                        registerBtAuthCode.setText(String.valueOf(msg.obj));
                        registerBtAuthCode.setBackgroundResource(R.drawable.shape_bt_auth_code_disable);
                        break;
                    case MSG.MSG_SEND_VERIFY_CODE_END:
                        if (isFinishing())
                            return;
                        registerBtAuthCode.setClickable(true);
                        registerBtAuthCode.setTextColor(getResources().getColor(R.color.app_color));
                        registerBtAuthCode.setText("发送验证码");
                        registerBtAuthCode.setBackgroundResource(R.drawable.shape_rect_app_color);
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        UserVO userVO = FastJsonUtil.getBean(object.toString(), "body", "", UserVO.class);
        userVO.setLoginName(StringUtil.getEditText(registerEtUsername));
        userVO.setInitialPassword(EncryptUtil.SHA1(StringUtil.getEditText(registerEtPassword)));
        //个人信息存储
        UserXML.setUserVO(this, userVO);
        showToast("注册成功");

        //判断是否为企业用户注册
        if(userType.equals(Constant.USER_TYPE_ADMIN)){
            AdminXML.setIsAudit(activity, userVO.getIsAudit());
            AdminXML.setEnterpriseId(activity, userVO.getEnterpriseId());
            go(EnterpriseAuthActivity.class);
            finish();
            return;
        }

        List<PointVO> pointVOList = FastJsonUtil.getListBean(object.toString(), "body", "rewardPointDetailList", PointVO.class);

        setAlias(userVO.getUseraccid().replace("-", ""));


        // 注册为个人用户
        if (userType.equals(Constant.USER_TYPE_PERSON)) {
            // 判断融云XML里是否有该用户对应的Token
//            if (RongCloudXML.getUserToken(this, userVO.getUseraccid()).equals("default")) {
//                LogUtils.e("XML里没有该用户userID对应的Token,正在服务端获取...");
//                // 如果没有则调接口获取token
//                BusinessRongIM.getUserRCToken(this, userVO.getUseraccid(), userVO.getUserName(), mHandler);
//            } else {
//                // 如果融云为断开状态  有token则直接连接融云
//                if (RongIM.getInstance().getCurrentConnectionStatus().equals(RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED)) {
//                    LogUtils.e("融云IM连接状态正常");
//                } else {
//                    LogUtils.e("直接从XML获取的Token连接融云");
//                    connect(RongCloudXML.getUserToken(this, userVO.getUseraccid()));
//                }
//
//            }

            UserXML.setTodayLogin(RegisterActivity.this, DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD));
            UserXML.setLoginStatus(RegisterActivity.this, UserXML.USER_IS_LOGIN_VALUE);



            if (ActivityTaskManager.getInstance().hasActivity(MainActivity.class)) {
                UserXML.setRegisterMoney(this, object.toString());

                finish();
            } else {
                ActivityTaskManager.getInstance().closeActivity(LoginActivity.class);
                GotoUtil.gotoActivity(RegisterActivity.this, MainActivity.class, true, "pointVOList", pointVOList);
            }
        } else {
            // 注册为专家用户
            GotoUtil.gotoActivity(RegisterActivity.this, SaveExpertInfoActivity.class, true);
        }
    }

    private void setAlias(String alias) {
        LogUtils.e(alias);
        if (TextUtils.isEmpty(alias)) {
            LogUtils.e("alias is empty");
            return;
        }
        if (!Utils.isValidTagAndAlias(alias)) {
            LogUtils.e("alias is not valid");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    @Override
    public void rightOnClick() {

    }

    @OnClick({R.id.register_bt_auth_code, R.id.register_bt_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.register_bt_auth_code:
                getAuthCode();
                break;
            case R.id.register_bt_register:
                getInputContent();
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getAuthCode() {

        mStrMobile = registerEtMobile.getText().toString();
        if (StringUtil.isStrEmpty(mStrMobile)) {
            showSnackbar("手机号不能为空");
            return;
        } else if (!RegexpUtil.isRegexpValidate(mStrMobile, RegexpUtil.MOBILE_REGEXP)) {
            showSnackbar("请输入合法手机号");
            return;
        }

        BusinessAccount.sendVerifyCode(this, mStrMobile, mHandler);
    }

    /**
     * 获取输入内容
     */
    private void getInputContent() {

        mStrUserName = registerEtUsername.getText().toString();
        mStrMobile = registerEtMobile.getText().toString();
        mStrAuthCode = registerEtAuthCode.getText().toString();
        mStrPassword = registerEtPassword.getText().toString();
        mStrAffirmPassword = registerEtAffirmPassword.getText().toString();

//        if (StringUtil.isStrEmpty(mStrUserName)) {
//            showSnackbar("用户名不能为空");
//            return;
//        }
//        if (mStrUserName.length() < 6 || mStrUserName.length() > 14) {
//            showSnackbar("用户名为6-14字符");
//            return;
//        }
//        if (!RegexpUtil.isRegexpValidate(mStrUserName, RegexpUtil.NOT_ONLY_NUM_REGEXP)) {
//            showSnackbar("用户名不能为纯数字");
//            return;
//        }
        if (StringUtil.isStrEmpty(mStrMobile)) {
            showSnackbar("手机号不能为空");
            return;
        }
        if (!RegexpUtil.isRegexpValidate(mStrMobile, RegexpUtil.MOBILE_REGEXP)) {
            showSnackbar("请输入合法手机号");
            return;
        }
        if (StringUtil.isStrEmpty(mStrAuthCode)) {
            showSnackbar("请填写验证码");
            return;
        }
        if (6 != mStrAuthCode.length()) {
            showSnackbar("请输入6位验证码");
            return;
        }
        if (StringUtil.isStrEmpty(mStrPassword)) {
            showSnackbar("请填写密码");
            return;
        }

//        if (mStrPassword.length() < 6 || mStrPassword.length() > 14) {
//            showSnackbar("密码为6-14字符");
//            return;
//        }
//
//        if (!RegexpUtil.isRegexpValidate(mStrPassword, RegexpUtil.LETTER_AND_NUMBER_REGEXP)) {
//            showSnackbar("密码必须为字母和数字组合");
//            return;
//        }
//
//        if (StringUtil.isStrEmpty(mStrAffirmPassword)) {
//            showSnackbar("请填写确认密码");
//            return;
//        }
//        if (!StringUtil.isStrEqual(mStrPassword, mStrAffirmPassword)) {
//            showSnackbar("两次密码输入不一致");
//            return;
//        }


        BusinessAccount.userRegisterAndLogin(this, mStrMobile, mStrMobile, mStrPassword, mStrAuthCode, userType, registerEtInviteCode.getText().toString(), openId, ID, accountType, mHandler);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.register_bt_register_for_expert)
    public void onViewClicked() {
        GotoUtil.gotoActivity(RegisterActivity.this, ExpertCooperationActivity.class);
    }
}
